﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using Codeplex.SPCleanup.SPUtilities.Cleanup;

namespace Codeplex.SPCleanup.FeatureReceivers
{
    public class ListCleanupUIFeatureReceiver : SPFeatureReceiver
    {
        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {

        }

        /// <summary>
        /// Enables the site for cleanup by adding the default values
        /// </summary>
        /// <param name="properties"></param>
        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            UpdateListCleanupSettingsForSite(properties.Feature.Parent as SPWeb,true);
        }

        /// <summary>
        /// Disables the site for cleanup by setting the enabled property to false
        /// </summary>
        /// <param name="properties"></param>
        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            UpdateListCleanupSettingsForSite(properties.Feature.Parent as SPWeb, false);
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            
        }

        /// <summary>
        /// Helper function called from activate and deactivate event. Enable it for site
        /// during activation and disable it during deactivation
        /// </summary>
        /// <param name="web">site(web) reference</param>
        /// <param name="enable">enable/disable for the site</param>
        private void UpdateListCleanupSettingsForSite(SPWeb web, bool enable)
        {            
            if (null != web)
            {
                SiteDefinition cleanupSiteDef = new SiteDefinition();
                cleanupSiteDef.ID = web.Site.ID;
                cleanupSiteDef.SiteUri = new Uri(web.Site.Url);
                cleanupSiteDef.Enabled = true;

                Site cleanupSite = new Site();
                cleanupSite.ID = web.ID;
                cleanupSite.Enabled = enable;

                cleanupSiteDef.Sites.Add(cleanupSite);

                ConfigManager.UpdateListCleanupSettings(cleanupSiteDef);
            }
        }
    }
}
